import 'nprogress/nprogress.css' // progress bar style

import NProgress from 'nprogress' // progress bar
import { MessagePlugin } from 'tdesign-vue-next'

// import type { RouteRecordRaw } from 'vue-router'
import router from '@/router'
import { getPermissionStore, useUserStore } from '@/store'
// import { PAGE_NOT_FOUND_ROUTE } from '@/utils/route/constant'

NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, from, next) => {
  console.log('from', from.path, from.name, to.path, to.name)
  NProgress.start()

  const userStore = useUserStore()
  if (userStore.token) {
    console.log('to', to.path, to.name)
    if (to.path === '/login') {
      next('/')
      return
    }
    try {
      // 如果用户没有 roles 信息，需要重新获取
      await userStore.getUserInfo()
      if (!userStore.roles.length) {
        await userStore.getUserInfo()
        // permissionStore.initRoutes(userStore.roles)
      }
      if (to.name && router.hasRoute(to.name)) {
        next()
      }
      else {
        next(`/`)
      }
    }
    catch (error: any) {
      MessagePlugin.error(error.message)
      userStore.logout()
      next({
        path: '/login',
        query: { redirect: encodeURIComponent(to.fullPath) },
      })
    }
  }
  else {
    const permissionStore = getPermissionStore()
    const { whiteListRouters } = permissionStore
    /* white list router */
    if (whiteListRouters.includes(to.path)) {
      next()
    }
    else {
      next({
        path: '/login',
        query: { redirect: encodeURIComponent(to.fullPath) },
      })
    }
  }
})

router.afterEach((to) => {
  if (to.path === '/login') {
    const userStore = useUserStore()
    const permissionStore = getPermissionStore()

    userStore.logout()
    permissionStore.restore()
    // server permission store
    // permissionStore.restoreRoutes();
  }
  NProgress.done()
})
